package com.cinc.ebc.mm.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cinc.ebc.mm.constant.PurOrderStatus;
import com.cinc.ebc.mm.entity.MmPurchaseOrder;
import com.cinc.ebc.mm.entity.MmPurchaseOrderDetail;
import com.cinc.ebc.mm.entity.MmPurchaseRequisition;
import com.cinc.ebc.mm.entity.MmPurchaseRequisitionDetail;
import com.cinc.ebc.mm.mapper.MmPurchaseOrderDetailMapper;
import com.cinc.ebc.mm.mapper.MmPurchaseOrderMapper;
import com.cinc.ebc.mm.mapper.MmPurchaseRequisitionDetailMapper;
import com.cinc.ebc.mm.model.*;
import com.cinc.ebc.mm.service.IMmPurchaseOrderService;
import com.cinc.ebc.mm.service.IMmPurchaseRequisitionService;
import com.cinc.ebc.mm.vo.MmPurchaseOrderDetailPage;
import com.cinc.ebc.mm.vo.MmRptPurOrderStatPage;
import org.apache.commons.lang3.StringUtils;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.util.oConvertUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @Description: 采购订单
 * @Author: jeecg-boot
 * @Date:   2022-03-20
 * @Version: V1.0
 */
@Service
public class MmPurchaseOrderServiceImpl extends ServiceImpl<MmPurchaseOrderMapper, MmPurchaseOrder> implements IMmPurchaseOrderService {

	@Autowired
	private MmPurchaseOrderMapper mmPurchaseOrderMapper;
	@Autowired
	private MmPurchaseOrderDetailMapper mmPurchaseOrderDetailMapper;
	@Autowired
	private MmPurchaseRequisitionDetailMapper mmPurchaseRequisitionDetailMapper;
	@Autowired
	private IMmPurchaseRequisitionService mmPurchaseRequisitionService;

	@Override
	@Transactional
	public void saveMain(MmPurchaseOrder mmPurchaseOrder, List<MmPurchaseOrderDetail> mmPurchaseOrderDetailList) {
		mmPurchaseOrderMapper.insert(mmPurchaseOrder);
		if(mmPurchaseOrderDetailList!=null && mmPurchaseOrderDetailList.size()>0) {
			List<String> reqDetailIdList = new ArrayList<>();
			for(MmPurchaseOrderDetail entity:mmPurchaseOrderDetailList) {
				//外键设置
				entity.setPid(mmPurchaseOrder.getId());
				mmPurchaseOrderDetailMapper.insert(entity);

				if(StringUtils.isNotBlank(entity.getReqDetailId())){
					reqDetailIdList.add(entity.getReqDetailId());
				}
			}
			// 更新采购申请
			if(oConvertUtils.listIsNotEmpty(reqDetailIdList)){
				mmPurchaseRequisitionDetailMapper.autoUpdatePurQtyByIdlist(reqDetailIdList);
				mmPurchaseRequisitionDetailMapper.autoUpdateStatusByIdlist(reqDetailIdList);
				QueryWrapper<MmPurchaseRequisitionDetail> queryWrapper = new QueryWrapper<MmPurchaseRequisitionDetail>().in("id",reqDetailIdList);
				List<MmPurchaseRequisitionDetail> reqDetailList = mmPurchaseRequisitionDetailMapper.selectList(queryWrapper);
				List<String> reqIdList = reqDetailList.stream().map(MmPurchaseRequisitionDetail::getPid).distinct().collect(Collectors.toList());
				mmPurchaseRequisitionService.autoUpdateStatus(reqIdList);
			}
		}
	}

	@Override
	@Transactional
	public void updateMain(MmPurchaseOrder mmPurchaseOrder,List<MmPurchaseOrderDetail> mmPurchaseOrderDetailList) throws Exception {
		mmPurchaseOrder.setCreateBy(null);
		mmPurchaseOrder.setCreateTime(null);
		mmPurchaseOrder.setSysOrgCode(null);
		mmPurchaseOrderMapper.updateById(mmPurchaseOrder);
		// 子表处理
		List<String> detailIdDelList= null;
		List<String> detailIdList = mmPurchaseOrderDetailMapper.selectIdListByMainId(mmPurchaseOrder.getId());
		List<String> reqDetailIdList = mmPurchaseOrderDetailMapper.selectReqDetailIdListByMainId(mmPurchaseOrder.getId());
		if(mmPurchaseOrderDetailList!=null && mmPurchaseOrderDetailList.size()>0) {
			List<String> curDetailIdList = mmPurchaseOrderDetailList.stream().map(MmPurchaseOrderDetail::getId).collect(Collectors.toList());
			detailIdDelList = detailIdList.stream().filter(detailId->!curDetailIdList.contains(detailId)).collect(Collectors.toList());
			for(MmPurchaseOrderDetail entity:mmPurchaseOrderDetailList) {
				if(StringUtils.isBlank(entity.getPid())){
					// 新增
					entity.setPid(mmPurchaseOrder.getId());
					mmPurchaseOrderDetailMapper.insert(entity);
				}else{
					// 修改
					mmPurchaseOrderDetailMapper.updateById(entity);
				}
				if(StringUtils.isNotBlank(entity.getReqDetailId())){
					reqDetailIdList.add(entity.getReqDetailId());
				}
			}
		}
		// 删除
		if(oConvertUtils.listIsNotEmpty(detailIdDelList)){
			QueryWrapper<MmPurchaseOrderDetail> orderDetailQueryWrapper = new QueryWrapper<>();
			orderDetailQueryWrapper.in("id", detailIdDelList);
			orderDetailQueryWrapper.ne("status", PurOrderStatus.STATUS_01);
			Integer delCount = mmPurchaseOrderDetailMapper.selectCount(orderDetailQueryWrapper);
			if(delCount > 0){
				throw new RuntimeException("非新建状态的采购明细，不能删除！");
			}

			mmPurchaseOrderDetailMapper.deleteLogicByIds(detailIdDelList);
		}
		// 更新采购申请单
		if(oConvertUtils.listIsNotEmpty(reqDetailIdList)){
			mmPurchaseRequisitionDetailMapper.autoUpdatePurQtyByIdlist(reqDetailIdList);
			mmPurchaseRequisitionDetailMapper.autoUpdateStatusByIdlist(reqDetailIdList);
			QueryWrapper<MmPurchaseRequisitionDetail> queryWrapper = new QueryWrapper<MmPurchaseRequisitionDetail>().in("id",reqDetailIdList);
			List<MmPurchaseRequisitionDetail> reqDetailList = mmPurchaseRequisitionDetailMapper.selectList(queryWrapper);
			List<String> reqIdList = reqDetailList.stream().map(MmPurchaseRequisitionDetail::getPid).distinct().collect(Collectors.toList());
			mmPurchaseRequisitionService.autoUpdateStatus(reqIdList);
		}
	}

	@Override
	@Transactional
	public void delMain(String id) {
		List<String> reqDetailIdList = mmPurchaseOrderDetailMapper.selectReqDetailIdListByMainId(id);
		mmPurchaseOrderDetailMapper.deleteByMainId(id);
		mmPurchaseOrderMapper.deleteById(id);
		// 更新采购申请单
		if(oConvertUtils.listIsNotEmpty(reqDetailIdList)){
			mmPurchaseRequisitionDetailMapper.autoUpdatePurQtyByIdlist(reqDetailIdList);
			mmPurchaseRequisitionDetailMapper.autoUpdateStatusByIdlist(reqDetailIdList);
		}
	}

	@Override
	@Transactional
	public void delBatchMain(List<String> idList) {
		for(String id:idList) {
			List<String> reqDetailIdList = mmPurchaseOrderDetailMapper.selectReqDetailIdListByMainId(id);
			mmPurchaseOrderDetailMapper.deleteByMainId(id);
			mmPurchaseOrderMapper.deleteById(id);
			// 更新采购申请单
			if(oConvertUtils.listIsNotEmpty(reqDetailIdList)){
				mmPurchaseRequisitionDetailMapper.autoUpdatePurQtyByIdlist(reqDetailIdList);
				mmPurchaseRequisitionDetailMapper.autoUpdateStatusByIdlist(reqDetailIdList);
			}
		}
	}

	@Override
	public IPage<MmPurchaseOrderDetailModel> detailPage(Page<MmPurchaseOrderDetailModel> page, MmPurchaseOrderDetailPage mmPurchaseOrderDetailPage) {
		String sql = QueryGenerator.installAuthJdbc(MmPurchaseOrder.class);
		return page.setRecords(mmPurchaseOrderMapper.selectDetailList(page, mmPurchaseOrderDetailPage, sql));
	}

	@Override
	public List<MmPurchaseOrderDetailModel> detailList(MmPurchaseOrderDetailPage mmPurchaseOrderDetailPage) {
		String sql = QueryGenerator.installAuthJdbc(MmPurchaseOrder.class);
		return mmPurchaseOrderMapper.selectDetailList(null, mmPurchaseOrderDetailPage, sql);
	}

	/**
	 * 删除明细
	 *
	 * @param id
	 * @return void
	 * @throws
	 */
	@Override
	@Transactional
	public void delDetail(String id) throws Exception {
		MmPurchaseOrderDetail purOrderDetail = mmPurchaseOrderDetailMapper.selectById(id);
		if(purOrderDetail == null){
			throw new RuntimeException("数据不存在，删除失败！");
		}
		if(!PurOrderStatus.STATUS_01.equals(purOrderDetail.getStatus())){
			throw new RuntimeException("当前状态不允许删除");
		}
		mmPurchaseOrderDetailMapper.deleteLogicById(id);
		// 处理主表记录
		String pid = purOrderDetail.getPid();
		QueryWrapper<MmPurchaseOrderDetail> queryWrapper = new QueryWrapper<MmPurchaseOrderDetail>()
				.eq("pid",pid).eq("del_flag","0");
		Integer detailCount = mmPurchaseOrderDetailMapper.selectCount(queryWrapper);
		if(detailCount == 0){
			mmPurchaseOrderMapper.deleteLogicById(purOrderDetail.getPid());
		}
		// 更新请购单状态
		if(oConvertUtils.isNotEmpty(purOrderDetail.getReqDetailId())){
			mmPurchaseRequisitionDetailMapper.autoUpdatePurQtyByIdlist(Arrays.asList(id));
			mmPurchaseRequisitionDetailMapper.autoUpdateStatusByIdlist(Arrays.asList(id));
			mmPurchaseRequisitionService.autoUpdateStatus(Arrays.asList(purOrderDetail.getPid()));
		}
	}

	@Override
	@Transactional
	public void delBatchDetail(List<String> idList) throws Exception {
		// 删除校验
		QueryWrapper<MmPurchaseOrderDetail> queryWrapper = new QueryWrapper<>();
		queryWrapper.in("id", idList);
		List<MmPurchaseOrderDetail> purchaseOrderDetailList = mmPurchaseOrderDetailMapper.selectList(queryWrapper);
		List<MmPurchaseOrderDetail> backList = new ArrayList<>();
		List<String> reqDetailIdList = new ArrayList<>();
		for(MmPurchaseOrderDetail purchaseOrderDetail : purchaseOrderDetailList){
			if(!PurOrderStatus.STATUS_01.equals(purchaseOrderDetail.getStatus())){
				backList.add(purchaseOrderDetail);
			}
			if(oConvertUtils.isNotEmpty(purchaseOrderDetail.getReqDetailId())){
				reqDetailIdList.add(purchaseOrderDetail.getReqDetailId());
			}
		}
		if(oConvertUtils.listIsNotEmpty(backList)){
			MmPurchaseOrder mmPurchaseOrder = mmPurchaseOrderMapper.selectById(backList.get(0).getPid());
			throw new RuntimeException("单据[" + mmPurchaseOrder.getOrderNo() + "," + backList.get(0).getLineNo()  + "]当前状态不能删除");
		}
		// 删除明细
		mmPurchaseOrderDetailMapper.deleteLogicByIds(idList);
		// 处理主表
		List<String> pidList = purchaseOrderDetailList.stream().map(MmPurchaseOrderDetail::getPid).distinct().collect(Collectors.toList());
		queryWrapper.clear();
		queryWrapper.in("pid", pidList).eq("del_flag", "0");
		List<MmPurchaseOrderDetail> otherDetailList = mmPurchaseOrderDetailMapper.selectList(queryWrapper);
		List<String> otherPidList = otherDetailList.stream().map(MmPurchaseOrderDetail::getPid).distinct().collect(Collectors.toList());
		List<String> pidDelList = pidList.stream().filter(pid -> !otherPidList.contains(pid)).collect(Collectors.toList());
		if(oConvertUtils.listIsNotEmpty(pidDelList)){
			mmPurchaseOrderMapper.deleteLogicBatchByIds(pidDelList);
		}

		// 更新采购申请单
		if(oConvertUtils.listIsNotEmpty(reqDetailIdList)){
			QueryWrapper<MmPurchaseRequisitionDetail> reqDetailQueryWrapper = new QueryWrapper<MmPurchaseRequisitionDetail>().in("id",reqDetailIdList);
			List<MmPurchaseRequisitionDetail> reqDetailList = mmPurchaseRequisitionDetailMapper.selectList(reqDetailQueryWrapper);
			List<String> reqIdList = reqDetailList.stream().map(MmPurchaseRequisitionDetail::getPid).distinct().collect(Collectors.toList());
			mmPurchaseRequisitionDetailMapper.autoUpdatePurQtyByIdlist(reqDetailIdList);
			mmPurchaseRequisitionDetailMapper.autoUpdateStatusByIdlist(reqDetailIdList);
			mmPurchaseRequisitionService.autoUpdateStatus(reqIdList);
		}
	}

	@Override
	public void delLogicMain(String id) throws RuntimeException {
		MmPurchaseOrder mmPurchaseOrder = mmPurchaseOrderMapper.selectById(id);
		if(mmPurchaseOrder == null){
			throw new RuntimeException("数据不存在");
		}
		if(!PurOrderStatus.STATUS_01.equals(mmPurchaseOrder.getStatus())){
			throw new RuntimeException("当前状态不能删除");
		}
		List<String> reqDetailIdList = mmPurchaseOrderDetailMapper.selectReqDetailIdListByMainId(id);
		mmPurchaseOrderDetailMapper.deleteLogicByMainId(id);
		mmPurchaseOrderMapper.deleteLogicById(id);
		// 更新采购申请单
		if(oConvertUtils.listIsNotEmpty(reqDetailIdList)){
			QueryWrapper<MmPurchaseRequisitionDetail> queryWrapper = new QueryWrapper<MmPurchaseRequisitionDetail>().in("id",reqDetailIdList);
			List<MmPurchaseRequisitionDetail> reqDetailList = mmPurchaseRequisitionDetailMapper.selectList(queryWrapper);
			List<String> reqIdList = reqDetailList.stream().map(MmPurchaseRequisitionDetail::getPid).distinct().collect(Collectors.toList());
			mmPurchaseRequisitionDetailMapper.autoUpdatePurQtyByIdlist(reqDetailIdList);
			mmPurchaseRequisitionDetailMapper.autoUpdateStatusByIdlist(reqDetailIdList);
			mmPurchaseRequisitionService.autoUpdateStatus(reqIdList);
		}
	}

	/**
	 * 采购统计查询
	 * @param page
	 * @param mmRptPurOrderStatPage
	 * @return
	 */
	@Override
	public IPage<MmRptPurOrderMaterialStatModel> queryRptMaterialStatList(Page<MmRptPurOrderMaterialStatModel> page, MmRptPurOrderStatPage mmRptPurOrderStatPage) {
		return page.setRecords(mmPurchaseOrderMapper.selectRptMaterialStatList(page, mmRptPurOrderStatPage));
	}

	/**
	 * 采购统计查询-物料-列合计
	 * @param mmRptPurOrderStatPage
	 * @return
	 */
	@Override
	public MmRptPurOrderMaterialStatTotalModel queryRptMaterialStatTotal(MmRptPurOrderStatPage mmRptPurOrderStatPage) {
		return mmPurchaseOrderMapper.selectRptMaterialStatTotal(mmRptPurOrderStatPage);
	}

	@Override
	public IPage<MmRptPurOrderSupplyStatModel> queryRptSupplyStatList(Page<MmRptPurOrderSupplyStatModel> page, MmRptPurOrderStatPage mmRptPurOrderStatPage) {
		return page.setRecords(mmPurchaseOrderMapper.selectRptSupplyStatList(page, mmRptPurOrderStatPage));
	}

	@Override
	public MmRptPurOrderSupplyStatTotalModel queryRptSupplyStatTotal(MmRptPurOrderStatPage mmRptPurOrderStatPage) {
		return mmPurchaseOrderMapper.selectRptSupplyStatTotal(mmRptPurOrderStatPage);
	}

	@Override
	public IPage<MmRptPurOrderBuyerStatModel> queryRptBuyerStatList(Page<MmRptPurOrderBuyerStatModel> page, MmRptPurOrderStatPage mmRptPurOrderStatPage) {
		return page.setRecords(mmPurchaseOrderMapper.selectRptBuyerStatList(page, mmRptPurOrderStatPage));
	}

	@Override
	public MmRptPurOrderBuyerStatTotalModel queryRptBuyerStatTotal(MmRptPurOrderStatPage mmRptPurOrderStatPage) {
		return mmPurchaseOrderMapper.selectRptBuyerStatTotal(mmRptPurOrderStatPage);
	}

	@Override
	public Map<String, BigDecimal> queryLatestPrice(String materialIds, String supplyId) {
		Map<String, BigDecimal> data = new HashMap<>();
		List<String> materialIdList = Arrays.asList(materialIds.split(","));
		for(String materialId : materialIdList){
			BigDecimal unitPrice = mmPurchaseOrderMapper.selectLatestPriceByMaterialId(materialId, supplyId);
			if(!data.containsKey(materialId)){
				data.put(materialId, unitPrice == null ? BigDecimal.ZERO : unitPrice);
			}
		}
		return data;
	}

	/**
	 * 供应商物料统计查询
	 * @param page
	 * @param detailPage
	 */
	@Override
	public void querySupplyMaterialStatPageList(Page<MmPurchaseOrderSupplyMaterialModel> page, MmPurchaseOrderDetailPage detailPage) {

		page.setRecords(mmPurchaseOrderMapper.selectSupplyMaterialStatList(page, detailPage, null));
	}
}
